<?php
namespace app\erp\model;

use think\Model;

class BrandApidb extends Model
{

    protected $pk = 'brand_api_id';

    protected $name = 'brand_api';

    protected $insert = [
        'partner_id' => PARTNER_ID,
        'site_id'
    ];

    protected function setSiteIdAttr($value)
    {
        if (! $value) {
            return SITE_ID;
        }
        if ($value == 0) {
            return null;
        }
        return $value;
    }

    public $param = array();

    protected function cache_name($name)
    {
        $new_arr = $this->param;
        $new_arr['partner_id'] = PARTNER_ID;
        if (! isset($new_arr['site_id'])) {
            $new_arr['site_id'] = SITE_ID;
        }
        ksort($new_arr);
        $param_str = http_build_query($new_arr);
        return md5($name . $param_str);
    }

    public function scopeBrandSign($query, $brand_sign)
    {
        $query->where('brand_sign', $brand_sign);
    }

    public function base($query)
    {
       /* $query->where('partner_id', PARTNER_ID);
        if (isset($this->param['site_id'])) {
            if ($this->param['site_id'] == 0 || $this->param['site_id'] == '') {
                $query->where('site_id', 'null');
            } else {
                $query->where('site_id', $this->param['site_id']);
            }
        } else {
            if (! empty(SITE_ID)) {
                $query->where('site_id', SITE_ID);
            } else {
                $query->where('site_id', 'null');
            }
        }*/
        if (isset($this->param['brand_sign']) && $this->param['brand_sign']) {
            $query->brandSign($this->param['brand_sign']);
        }
    }

    public function ajaxSave()
    {
        $chk_find = $this->find();
        if ($chk_find) {
            $chk_find = $chk_find->toArray();
            $this->save($this->param, [
                'brand_api_id' => $chk_find['brand_api_id']
            ]);
        } else {
            $this->isUpdate(false)->save($this->param);
        }
        return 'success';
    }

    public function ajaxFind()
    {
        $data = $this->find();
        if ($data) {
            $data = $data->toArray();
        } else {
            $data['option'] = '';
        }
        return $data;
    }
}